"""
题目：实现双链表的节点定义、链表创建函数和正反向遍历函数。
"""


class Node:
    def __init__(self, val=0, prev=None, next=None):
        self.val = val  # 节点存储的值
        self.prev = prev  # 指向前一个节点的指针
        self.next = next  # 指向后一个节点的指针


def create_doubly_linked_list(arr):
    if not arr:  # 处理空列表情况
        return None

    # 创建头节点
    head = Node(arr[0])
    current = head  # 当前节点指针

    # 遍历剩余元素，创建节点并建立双向链接
    for val in arr[1:]:
        new_node = Node(val)  # 创建新节点
        current.next = new_node  # 当前节点的next指向新节点
        new_node.prev = current  # 新节点的prev指向当前节点
        current = new_node  # 移动当前节点指针

    return head  # 返回头节点


def traverse_forward(head):
    """正向遍历（从头到尾）"""
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next  # 向后移动
    return result


def traverse_backward(tail):
    """反向遍历（从尾到头）"""
    result = []
    current = tail
    while current:
        result.append(current.val)
        current = current.prev  # 向前移动
    return result


# 测试
arr = [1, 2, 3, 4, 5]
head = create_doubly_linked_list(arr)

# 获取尾节点（用于反向遍历）
tail = head
while tail and tail.next:
    tail = tail.next

print("正向遍历:", traverse_forward(head))  # 输出: [1, 2, 3, 4, 5]
print("反向遍历:", traverse_backward(tail))  # 输出: [5, 4, 3, 2, 1]
